var BSTMG = BSTMG || {};
BSTMG.voucherManager = {
	DATALIST: [{
		"itemname": "企业用户",
		"boundtype": 1,
		hover: {
			url: '/sysAdmin/voucher/companyList',
			callback: function(data){
				var newdata = {"items":[]};
				$.each(data.items,function(index,val){
					var id = val["userId"],
						name = val["userEmail"];
					
					newdata.items.push({
						"id": id,
						"name": name
					});
				});
				return newdata;
			}
		},
		clickcallback: function(){}
	},{
		"itemname":"个人用户",
		"boundtype": 2,
		hover: {
			url: '/sysAdmin/voucher/userList',
			callback: function(data){
				var newdata = {"items":[]};
				$.each(data.items,function(index,val){
					var id = val["userId"],
						name = val["userTel"];
					
					if(name == null || name == ""){
						name = val["userEmail"];
					}
					newdata.items.push({
						"id": id,
						"name": name
					});
				});
				return newdata;
			}
		},
		clickcallback: function(){}
	},{
		"itemname":"应用编号",
		"boundtype": 3,
		hover: {
			url: '/sysAdmin/voucher/mpList',
			callback: function(data){
				var newdata = {"items":[]};
				$.each(data.items,function(index,val){
						var id = val["goodsId"],
							name = val["goodsName"];
						newdata.items.push({
							"id": id,
							"name": name
						});
				});
				return newdata;
			}
		},
		clickcallback: function(){}
	}],
	
	CZDATALIST: [{
		"itemname": "企业用户",
		"boundtype": 1,
		hover: {
			url: '/sysAdmin/voucher/companyList',
			callback: function(data){
				var newdata = {"items":[]};
				$.each(data.items,function(index,val){
					var id = val["userId"],
						name = val["userEmail"];
					
					newdata.items.push({
						"id": id,
						"name": name
					});
				});
				return newdata;
			}
		},
		clickcallback: function(){}
	},{
		"itemname":"个人用户",
		"boundtype": 2,
		hover: {
			url: '/sysAdmin/voucher/userList',
			callback: function(data){
				var newdata = {"items":[]};
				$.each(data.items,function(index,val){
					var id = val["userId"],
						name = val["userTel"];
					
					if(name == null || name == ""){
						name = val["userEmail"];
					}
					newdata.items.push({
						"id": id,
						"name": name
					});
				});
				return newdata;
			}
		},
		clickcallback: function(){}
	}],
	
	init: function(){
		var that = this;
		//分页功能
		that.showVoucherList();
		//绑定新增按钮
		that.addVoucher();
		//根据代金券编号查询代金券
		this.searchVoucher();
		//编辑，保存
		that.editAndSave();
		//联动菜单
		that.dynamicMenu();
	},
	dynamicMenu: function(){
		var that = this;
		BSTMG.common && BSTMG.common.hjhMenu && BSTMG.common.hjhMenu();	//插件触发
		var $voucherList = $("#voucherList"),
			$tabody = $voucherList.find('tbody');
			
		$(".dynadown").dynaMenu(that.DATALIST);
		
	},
	showVoucherList: function(state){
		BSTMG.common.hjhPages('/sysAdmin/voucher/voucherList/search',{state:state},function(data){
			var voucherList = data.voucherList;
            var $tbody = $("#voucherList tbody"),
                html = '';
            if(voucherList.length > 0) {
				for(var i=0;i<voucherList.length;i++){
					var voucherInfo = voucherList[i];
					html += '<tr>';
					html += '<td>'+(i+1)+'</td>';
					html += '<td class="td_id">'+voucherInfo.voucherNum+'</td>';
					html += '<td class="td_amount">'+parseFloat(voucherInfo.voucherMoney).toFixed(2)+'</td>';
					html += '<td class="td_date">'+toDate(new Date(voucherInfo.createTime), "yyyy-MM-dd hh:mm:ss")+'</td>';
					html += '<td class="td_start">'+toDate(new Date(voucherInfo.onsetTime), "yyyy-MM-dd")+'</td>';
					html += '<td class="td_end">'+toDate(new Date(voucherInfo.deadTime), "yyyy-MM-dd")+'</td>';
					html += '<td class="td_type">'+setVoucherType(voucherInfo.voucherType)+'</td>';
					html += '<td class="td_infor" data-boundtype="'+voucherInfo.boundType+'" data-id="'+voucherInfo.boundId+'">'+setBoundInfo(voucherInfo)+'</td>';
					html += '<td class="td_creater">'+voucherInfo.createName+'</td>';
					html += '<td class="td_status" data-id="'+voucherInfo.state+'">'+setVoucherState(voucherInfo)+'</td>';
					
					var deadTime = toDate(new Date(voucherInfo.deadTime), "yyyy-MM-dd");
					var nowTime = toDate(new Date(), "yyyy-MM-dd");
					
						if(voucherInfo.state == 0){
							if(deadTime < nowTime){
								html += '<td></td>';
							}else{
								html += '<td><a class="btn btn-danger editrow">编辑</a></td>';
							}
						}else{
							html += '<td></td>';
						}
					
					html += '</tr>';
				}
				$tbody.html(html);
            } else {
                var $tr = '<tr class="odd"><td colspan="11" style="text-align:center">暂无数据！</td></tr>';
                $tbody.html($tr);
            }
		});
	},
	addVoucher: function(){
		var that = this,
			$addVoucher = $("#addVoucher");
		$addVoucher.on("click",function(){
			that.addRowVoucher();
		});
	},
	searchVoucher: function(){
		var that = this,
			$searchVoucher = $("#searchVoucher");
		$searchVoucher.on("click",function(){
			var vnumber = $('#vnumber').val();
			if($.trim(vnumber) == '')return BSTYUN.dialog.warn('代金券编号为空！');
			else{
				BSTMG.common.hjhPages('/sysAdmin/voucher/voucherList/search',{vnumber:vnumber},function(data){
					var voucherList = data.voucherList;
		            var $tbody = $("#voucherList tbody"),
		                html = '';
		            if(voucherList.length > 0) {
						for(var i=0;i<voucherList.length;i++){
							var voucherInfo = voucherList[i];
							html += '<tr>';
							html += '<td>'+(i+1)+'</td>';
							html += '<td class="td_id">'+voucherInfo.voucherNum+'</td>';
							html += '<td class="td_amount">'+parseFloat(voucherInfo.voucherMoney).toFixed(2)+'</td>';
							html += '<td class="td_date">'+toDate(new Date(voucherInfo.createTime), "yyyy-MM-dd hh:mm:ss")+'</td>';
							html += '<td class="td_start">'+toDate(new Date(voucherInfo.onsetTime), "yyyy-MM-dd")+'</td>';
							html += '<td class="td_end">'+toDate(new Date(voucherInfo.deadTime), "yyyy-MM-dd")+'</td>';
							html += '<td class="td_type">'+setVoucherType(voucherInfo.voucherType)+'</td>';
							html += '<td class="td_infor" data-boundtype="'+voucherInfo.boundType+'" data-id="'+voucherInfo.boundId+'">'+setBoundInfo(voucherInfo)+'</td>';
							html += '<td class="td_creater">'+voucherInfo.createName+'</td>';
							html += '<td class="td_status" data-id="'+voucherInfo.state+'">'+setVoucherState(voucherInfo)+'</td>';
							if(voucherInfo.state == 0){
								html += '<td><a class="btn btn-danger editrow">编辑</a></td>';
							}else{
								html += '<td></td>';
							}
							html += '</tr>';
						}
						$tbody.html(html);
		            } else {
		                var $tr = '<tr class="odd"><td colspan="11" style="text-align:center">暂无数据！</td></tr>';
		                $tbody.html($tr);
		                BSTYUN.dialog.warn('代金券不存在，请重新输入!');
		            }
				});

			}
		});
	},
	editAndSave: function(){
		var that = this,
			$voucherList = $("#voucherList"),
			$tabody = $voucherList.find('tbody');
		var tools = this.tools;
		$tabody.on("click","a.editrow",function(){
			var $this = $(this),
				$tr = $this.parents('tr'),
				$serial = $tr.find('td:first-child'),				//序号
				$voucherid = $tr.find('.td_id'),					//代金券编号
				$voucher_amount = $tr.find('.td_amount'),			//代金券金额
				$voucher_date = $tr.find('.td_date'),				//创建时间
				$voucher_start = $tr.find('.td_start'),				//代金券开始时间
				$voucher_end = $tr.find('.td_end'),					//代金券结束时间
				$voucher_type = $tr.find('.td_type'),				//类型
				$voucher_status = $tr.find('.td_status'),			//状态
				$voucher_createName = $tr.find('.td_creater'),		//创建人
				$voucher_bind = $tr.find(".td_infor");				//绑定信息
			
			var serial = $.trim($serial.text()),
				id = $.trim($voucherid.text()),
				amount = $.trim($voucher_amount.text()),
				date = $.trim($voucher_date.text()),
				start = $.trim($voucher_start.text()),
				end = $.trim($voucher_end.text()),
				typename = $.trim($voucher_type.text()),
				bindinfor = $.trim($voucher_bind.text()),
				bindtype = $.trim($voucher_bind.attr("data-boundtype")),
				bindid = $.trim($voucher_bind.attr("data-id")),
				createName = $.trim($voucher_createName.text()),
				status = $.trim($voucher_status.attr("data-id")),
				statusName = $.trim($voucher_status.text());
			var	html = '<tr><td>'+serial+'</td><td class="td_id"><input type="text" class="form-control voucher_id" placeholder="代金券编号,系统生成" value="'+id+'" disabled></td><td class="td_amount"><input type="text" class="form-control input_voucher" placeholder="代金券金额" value="'+amount+'"></td><td class="td_date"><input type="text" class="form-control voucher_date" value="'+date+'" disabled></td><td class="td_start"><input type="text" class="form-control pull-left startTime" value="'+start+'"></td><td class="td_end"><input type="text" class="form-control endTime" value="'+end+'"></td><td class="td_type"><select class="form-control type"><option value="1">充值</option><option value="2">消费</option></select></td><td><div class="dynadown"><button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">请选择<span class="caret"></span></button></div></td><td class="td_creater">'+createName+'</td><td class="td_status" data-id="'+status+'">'+statusName+'</td><td><a class="btn btn-primary saverow">保存</a></td></tr>';
			var $edit = $(html),
				$start = $edit.find('.startTime'),
				$end = $edit.find('.endTime'),
				$type = $edit.find('.type');
			$start.daterangepicker({
				 startDate: start,
			     endDate: end,
				 minDate : new Date(date).format('yyyy-MM-dd'),
				 opens: 'right',
				 timePickerIncrement: 30, 
				 format: 'YYYY-MM-DD',
				 locale: {applyLabel: '应用',cancelLabel: '取消',fromLabel:'起效时间',toLabel: '失效时间'}
			 }).on("applydate",function(event,data){
				  var $this = $(this),
				  	  start = data.picker.startDate,
				  	  end = data.picker.endDate;
				  $start.val(start.format('YYYY-MM-DD'));
				  $end.val(end.format('YYYY-MM-DD'));
			});
			

			$edit.on('click','input.endTime',function(){
				$start.trigger("click");
			 }).on("keydown","input.endTime,input.startTime",function(event){
				 return false;
			 });
			$edit.find(".input_voucher").on("blur",function(event){
				var $this = $(this),
					value = $.trim($this.val());
				if(value == ''){
					BSTYUN.dialog.warn('代金券金额不能为空！');
					return false;
				}
				if(isNaN(value)){
					BSTYUN.dialog.warn('请输入正确的代金券金额！');
					$this.focus();
					return false;
				}
				if(value == 0 || value.split("-").length > 1){
					BSTYUN.dialog.warn('请输入正确的代金券金额！');
					$this.focus();
					return false;
				}
			});
			$edit.find('.type').val(tools.getTypeFromString(type)).end().find('.status').val(tools.getStatusFromString(status));
			
			$type.on('change',function(){
				var type = $type.val(),
					DATALIST = that.DATALIST;
				if(type == 1) DATALIST = that.CZDATALIST;
				else DATALIST = that.DATALIST;
				
				$edit.find(".dynadown").parent().empty().html('<div class="dynadown"><button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">请选择<span class="caret"></span></button></div>').find(".dynadown").dynaMenu(DATALIST);
			}).prop("disabled",true);
			
			$tr.replaceWith($edit);
			
			//代金券类型,select必须插入到dom中才可以改变值
			typename == '充值' ? $type.val('1') : $type.val('2') ;
			var type = $type.val(),
				DATALIST = that.DATALIST;
			if(type == 1) DATALIST = that.CZDATALIST;
			else DATALIST = that.DATALIST;
			$edit.find(".dynadown").dynaMenu(DATALIST).find('.btn').attr("data-boundtype",bindtype).attr("data-value",bindinfor).attr("data-id",bindid).html(bindinfor+'<span class="caret"></span>');;

		}).on("click","a.saverow",function(){
			var $this = $(this),
				$tr = $this.parents("tr");
			
			var serial = $.trim($tr.find("td:first-child").text()),
				id = $.trim($tr.find("td .voucher_id").val()),
				amount = $.trim($tr.find("td .input_voucher").val()),
				date = $.trim($tr.find("td .voucher_date").val()),
				start = $.trim($tr.find("td .startTime").val()),
				end = $.trim($tr.find("td .endTime").val()),
				type = $.trim($tr.find("td .type").val()),
				status = $.trim($tr.find(".td_status").attr("data-id")),
				createname = $.trim($tr.find(".td_creater").text()),
				userid = $.trim($tr.find("td .dynadown button").attr("data-id")),
				uservalue = $.trim($tr.find("td .dynadown button").attr("data-value")),
				boundType = $.trim($tr.find("td .dynadown button").attr("data-boundtype"));

			if( amount == '' ){BSTYUN.dialog.warn('代金券金额不能为空！');return false;}
			if( start == '' ){BSTYUN.dialog.warn('代金券起效时间不能为空！');return false;}
			if(  start < date.replace( /\s.*/ ,"" ) ){BSTYUN.dialog.warn('起效时间不能小于当前日期！');return false;}
			if( boundType == '' ){BSTYUN.dialog.warn('绑定信息不能为空！');return false;}
			
			var params = {
					voucherNum : id,
					voucherMoney : amount,
					createTime : date,
					onsetTime : start,
					deadTime : end,
					voucherType : type,
					state : status,
					boundType : boundType,
					boundId : userid 
				};
			$.ajax({
	            url: '/sysAdmin/operate/voucher/addVoucher',
	            type: 'post',
	            dataType: 'json',
	            data: params,
	            success: function(data) {
	            	if(!data.isSuccess){BSTYUN.dialog.warn('代金券新增失败，请稍后再试!');return false;}
	            	var html = '<tr><td>'+serial+'</td><td class="td_id">'+data.voucher.voucherNum+'</td><td class="td_amount">'+amount+'</td><td class="td_date">'+date+'</td><td class="td_start">'+start+'</td><td class="td_end">'+end+'</td><td class="td_type">'+tools.getVoucherType(type)+'</td><td class="td_infor" data-boundtype="'+boundType+'" data-id="'+userid+'">'+uservalue+'</td><td class="td_creater">'+createname+'</td><td class="td_status" data-id="'+status+'">'+tools.getVoucherStatus(status)+'</td><td><a class="btn btn-danger editrow">编辑</a></td></tr>';
	            	$tr.replaceWith(html);
	            },
	            error: function(event) {
	                BSTYUN.dialog.warn('网络异常，请稍后尝试');
	            }
	        });
			
		});
	},
	addRowVoucher: function(){
		var that = this,
			tools = this.tools;
		var $voucherList = $("#voucherList"),
			$tabody = $voucherList.find('tbody'),
			isExisted = !!$tabody.find('.addrow').length,
			adminName = $("#adminName").val();
		var last = $.trim($tabody.find('tr:last-child').find('td:first-child').text());	//循序递增
		var date = new Date().format('yyyy-MM-dd hh:mm:ss');
		try{
			if(isNaN(last)){
				last = 0;
				$tabody.find('tr:first-child').remove();
			}
			last = parseInt(last) + 1;
		}catch(e){
			if(window.console && console.warn){
				console.warn("增加行出错,序号错误");
			}
		}
		var	html = '<tr class="addrow"><td>'+last+'</td><td class="td_id"><input type="text" class="form-control voucher_id" placeholder="代金券编号,系统生成" disabled></td><td class="td_amount"><input type="text" class="form-control input_voucher" placeholder="代金券金额"></td><td class="td_date"><input type="text" class="form-control voucher_date" value="'+date+'" disabled></td><td class="td_start"><input type="text" class="form-control pull-left startTime"></td><td class="td_end"><input type="text" class="form-control endTime"></td><td class="td_type"><select class="form-control type"><option value="1">充值</option><option value="2">消费</option></select></td><td><div class="dynadown"><button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">请选择<span class="caret"></span></button></div></td><td class="td_creater">'+adminName+'</td><td class="td_status" data-id="0">未使用</td><td><a class="btn btn-primary savenewrow">保存</a></td></tr>';
		if(isExisted){
			//可以增加闪光提示
			return false;
		}else{
			var $newrow = $(html),
				$start = $newrow.find('input.startTime'),
				$end = $newrow.find('input.endTime');
			var $voucherid = $newrow.find('.voucher_id'),				//代金券编号
				$voucher_amount = $newrow.find('.input_voucher'),		//代金券金额
				$voucher_date = $newrow.find('.voucher_date'),			//创建时间
				$voucher_start = $newrow.find('.startTime'),			//代金券开始时间
				$voucher_end = $newrow.find('.endTime'),				//代金券结束时间
				$voucher_type = $newrow.find('.type'),					//类型
				$status = $newrow.find(".td_status"),						//状态
//				$voucher_createName = $newrow.find('.td_creater'),		//创建人
				$userbutton = $newrow.find(".dynadown button");

			//$userbutton.attr("data-id",id).attr("data-value",txt).attr("data-boundtype",boundtype);
			$start.daterangepicker({
				 minDate : new Date().format('yyyy-MM-dd'),
				 opens: 'right',
				 timePickerIncrement: 30, 
				 format: 'YYYY-MM-DD',
				 locale: {applyLabel: '应用',cancelLabel: '取消',fromLabel:'起效时间',toLabel: '失效时间'}
			 }).on("applydate",function(event,data){
				  var $this = $(this),
				  	  start = data.picker.startDate,
				  	  end = data.picker.endDate;
				  $start.val(start.format('YYYY-MM-DD'));
				  $end.val(end.format('YYYY-MM-DD'));
			 });
			
			$newrow.find(".dynadown").dynaMenu(that.CZDATALIST);
			
			$voucher_type.on('change',function(){
				
				var type = $(this).val(),
					DATALIST = that.DATALIST;
				if(type == 1) DATALIST = that.CZDATALIST;
				else DATALIST = that.DATALIST;
				
				$newrow.find(".dynadown").parent().empty().html('<div class="dynadown"><button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">请选择<span class="caret"></span></button></div>').find(".dynadown").dynaMenu(DATALIST);
			});
			$newrow.find(".input_voucher").on("blur",function(event){
				var $this = $(this),
					value = $.trim($this.val());
				if(value == ''){
					BSTYUN.dialog.warn('代金券金额不能为空！');
					return false;
				}
				if(isNaN(value)){
					BSTYUN.dialog.warn('请输入正确的代金券金额！');
					$this.focus();
					return false;
				}
				if(value == 0 || value.split("-").length > 1){
					BSTYUN.dialog.warn('请输入正确的代金券金额！');
					$this.focus();
					return false;
				}
			});
			$newrow.on('click','input.endTime',function(){
				$start.trigger("click");
			 }).on("keydown","input.endTime,input.startTime",function(event){
				 return false;
			 });
			$newrow.on('click','.savenewrow',function(){
				console.log($userbutton)
				var id = $.trim($voucherid.val()),
					amount = $.trim($voucher_amount.val()),
					date = $.trim($voucher_date.val()),
					start = $.trim($voucher_start.val()),
					end = $.trim($voucher_end.val()),
					type = $.trim($voucher_type.val()),
					status = $.trim($status.attr("data-id")),
					//createName = $.trim($voucher_createName.val()),
					$userbutton = $(this).parents("tr").find(".dynadown button");
				var	userid = $.trim($userbutton.attr("data-id")),
					uservalue = $.trim($userbutton.attr("data-value")),
					boundType = $.trim($userbutton.attr("data-boundtype"));
				
				if( amount == '' ){BSTYUN.dialog.warn('代金券金额不能为空！');return false;}
				if( start == '' ){BSTYUN.dialog.warn('代金券起效时间不能为空！');return false;}
				if( start < date.replace( /\s.*/ ,"" ) ){ BSTYUN.dialog.warn('起效时间不能小于当前日期！');return false;}
				if( boundType == '' ){BSTYUN.dialog.warn('绑定信息不能为空！');return false;}
				
				var params = {
						voucherNum : id,
						voucherMoney : amount,
						createTime : date,
						onsetTime : start,
						deadTime : end,
						voucherType : type,
						state : status,
						boundType : boundType,
						boundId : userid 
					};
				$.ajax({
	                url: '/sysAdmin/operate/voucher/addVoucher',
	                type: 'post',
	                dataType: 'json',
	                data: params,
	                success: function(data) {
	                	if(!data.isSuccess){BSTYUN.dialog.warn('代金券新增失败，请稍后再试!');return false;}
	                	var html = '<tr><td>'+last+'</td><td class="td_id">'+data.voucher.voucherNum+'</td><td class="td_amount">'+amount+'</td><td class="td_date">'+date+'</td><td class="td_start">'+start+'</td><td class="td_end">'+end+'</td><td class="td_type">'+tools.getVoucherType(type)+'</td><td class="td_infor" data-boundtype="'+boundType+'" data-id="'+userid+'">'+uservalue+'</td><td class="td_creater">'+adminName+'</td><td class="td_status"  data-id="'+status+'">'+tools.getVoucherStatus(status)+'</td><td><a class="btn btn-danger editrow">编辑</a></td></tr>';
	                	$newrow.replaceWith(html);
	                },
	                error: function(event) {
	                    BSTYUN.dialog.warn('网络异常，请稍后尝试');
	                }
	            });
			 });
			$tabody.append($newrow);
		};
	},
	//辅助函数
	tools: {
		getVoucherType: function(type){
			return type == '1' ?
					'充值' :
					'消费' ;
		},
		getVoucherStatus: function(status){
			return status == '0' ?
					'未使用' :
					'已使用' ;
		},
		getTypeFromString: function(str){
			switch(str){
				case '充值':
					return 1;
					break;
				case '消费':
					return 2;
					break;
				default:
					return 0;
					break;
			}
		},
		getStatusFromString: function(str){
			switch(str){
				case '未使用':
					return 0;
					break;
				case '已使用':
					return 1;
					break;
				default:
					return 0;
					break;
			}
		}
	}
}

$(function(){
	BSTMG.voucherManager.init();
	
	$('#state').on('change',function(){
		var state = $('#state').val();
		if(state == '') state = -1;
		BSTMG.voucherManager.showVoucherList(state);
	});
});

//设置付款状态
function setVoucherState(voucher){
	var para = voucher.state;
	var deadTime = toDate(new Date(voucher.deadTime), "yyyy-MM-dd");
	var nowTime = toDate(new Date(), "yyyy-MM-dd");
	
	if (para == "0") {
		if(deadTime < nowTime){
			return "已过期";
		}else{
			return "未使用";
		}
	} else if (para == "1") {
		return "已使用";
	}
	
}

//设置绑定信息名称
function setBoundInfo(voucherInfo){
	if(voucherInfo.boundType == 1){
		return voucherInfo.boundUserEmail;
	}else if(voucherInfo.boundType == 2){
		if(voucherInfo.boundUserEmail != null && voucherInfo.boundUserEmail != ''){
			return voucherInfo.boundUserEmail;
		}else{
			return voucherInfo.boundUserTell;
		}
	}else if(voucherInfo.boundType == 3){
		return voucherInfo.boundProductName;
	}
}

//设置代金券类型
function setVoucherType(para){
	if (para == "1") {
		return "充值";
	} else if (para == "2") {
		return "消费";
	}
}
Date.prototype.format = function(fmt){
  var o = {   
    "M+" : this.getMonth()+1,                 //月份   
    "d+" : this.getDate(),                    //日   
    "h+" : this.getHours(),                   //小时   
    "m+" : this.getMinutes(),                 //分   
    "s+" : this.getSeconds(),                 //秒   
    "q+" : Math.floor((this.getMonth()+3)/3), //季度   
    "S"  : this.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
}
